package org.boot.easyapi.core.util.excelconfig;

import org.boot.easyapi.util.jdbc.JdbcUtil;
import org.boot.easyapi.pojo.db.TableDTO;
import org.boot.easyapi.util.spring.SpringUtil;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static org.boot.easyapi.exception.BusinessException.exception;

public class ExcelConfigUtil {


    /**
     * 校验excel配置json表达式
     * @param tableName
     * @param configJson
     * @return
     */
    public static boolean checkExcelConfigJsonExpression(String tableName, Map<String, Object> configJson) {
        if (configJson == null) return false;
        JdbcTemplate jdbcTemplate = SpringUtil.getBean(JdbcTemplate.class);
        List<TableDTO> table = JdbcUtil.getTable(jdbcTemplate, tableName);
        if (table == null || table.isEmpty()) return false;
        //取出table中nullable为false的数据
        List<TableDTO> nullableColumns = table.stream().filter(column -> !column.getNullable()).collect(Collectors.toList());
        for (TableDTO column : nullableColumns) {
            if (!configJson.containsValue(column.getName())) throw exception("excel配置json校验异常：表中[" + column.getName() + "]字段为非空字段!");
        }
        return true;
    }
}
